package com.itheima.health.security;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.SysUser;
import com.itheima.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @program: itcast_health
 * @create: 2019-10-28 16:02
 * @author: li he
 * @description:
 */
public class SecurityConfigUserService implements UserDetailsService {

    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = userService.loadUserByUsername(username);

        if (sysUser != null) {
            Collection<GrantedAuthority> authorityList = new ArrayList<>();

            for (Role role : sysUser.getRoles()) {

                for (Permission permission : role.getPermissions()) {
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getKeyword());
                    authorityList.add(authority);
                }
            }
            UserDetails userDetails = new User(sysUser.getUsername(), sysUser.getPassword(), authorityList);

            return userDetails;
        }
        return null;
    }
}